package com.clothes.act;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.clothes.R;
import com.clothes.adp.ItemAdapter;
import com.clothes.app.BaseUrl;
import com.clothes.http.JsonCallBack;
import com.clothes.mdoel.ClothesInfo;
import com.clothes.mdoel.ClothesTable;
import com.clothes.mdoel.ServerInfo;
import com.clothes.utils.DateTool;
import com.clothes.utils.StringUtils;
import com.clothes.views.CustomGridView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 领货
 */
public class GetProduct extends BaseActivity {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.et_gh)
    EditText etGh;
    @Bind(R.id.et_kh)
    EditText etKh;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_size_num)
    TextView mTvSizeNum;
    @Bind(R.id.gv_size)
    CustomGridView mGvSize;
    @Bind(R.id.tv_color_num)
    TextView mTvColorNum;
    @Bind(R.id.gv_color)
    CustomGridView mGvColor;

    private List<String> colors = new ArrayList<>();
    private ItemAdapter colorAdapter;
    private List<String> sizes = new ArrayList<>();
    private ItemAdapter sizeAdapter;
    private List<String> colorNums = new ArrayList<>();
    private int colorNum;

    @Override
    public void initView() {
        setContentView(R.layout.activity_get_product);
    }

    @Override
    public void initData() {
        tvTitle.setText("领货");
        setTime(5);
        tvTime.setText(DateTool.getStringDate(System.currentTimeMillis(), "yyyy-MM-dd HH:mm"));
        etKh.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String res = charSequence.toString();
                if (res.length() > 3) {
                    getDataByKh(res);
                }else {
                    if (res.length() == 3){
                        setError();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        etGh.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String res = s.toString();
                if(res.length() > 1){
                    getNameByNum(res);
                }else {
                    mTvName.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        colorAdapter = new ItemAdapter(this,colors);
        mGvColor.setAdapter(colorAdapter);
        sizeAdapter = new ItemAdapter(this,sizes);
        mGvSize.setAdapter(sizeAdapter);

        colorAdapter.setItemClick(new ItemAdapter.onItemClick() {
            @Override
            public void click(int i) {
                colorNum = Integer.parseInt(colorNums.get(i));
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_time,R.id.btn_get})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_time:
                timePickerView.show();
                break;
            case R.id.btn_get:
                submit();
                break;
        }
    }

    @Override
    protected void setTimeText(String time) {
        tvTime.setText(time);
    }

    //领货
    private void submit() {
        String time = tvTime.getText().toString();
        String gh = etGh.getText().toString();
        String kh = etKh.getText().toString();
        String color = colorAdapter.getClickItem();
        String size = sizeAdapter.getClickItem();
        String num = etNum.getText().toString();
        if (gh.equals("")) {
            showToast("请输入工号");
            return;
        }
        if (kh.equals("")) {
            showToast("请输入款号");
            return;
        }
        if (color.equals("")) {
            showToast("请选择颜色");
            return;
        }
        if (size.equals("")) {
            showToast("请选择尺寸");
            return;
        }
        if (num.equals("")) {
            showToast("请输入数量");
            return;
        }
        if (parseInt(num) > colorNum) {
            showToast("登记数量不足");
            return;
        }
        ClothesTable clothes = new ClothesTable();
        clothes.setClaimedDate(time);
        clothes.setWorkerNum(gh);
        clothes.setModelNumber(kh);
        clothes.setColor(color);
        clothes.setSize(size);
        clothes.setClaimed(parseInt(num));
        String json = new Gson().toJson(clothes);
        post(json, BaseUrl.ClAIM_CLOTHES);
    }

    @Override
    protected void onSuccess(String res) {
        showToast("领货成功");
        finish();
    }

    //根据款号请求
    private void getDataByKh(String khNo) {
        OkGo.<ServerInfo<List<ClothesInfo>>>get(BaseUrl.LH1).params("modelNumber", khNo)
                .execute(new JsonCallBack<ServerInfo<List<ClothesInfo>>>() {
                    @Override
                    public void onSuccess(Response<ServerInfo<List<ClothesInfo>>> response) {
                        ServerInfo serverInfo = response.body();
                        List<ClothesInfo> list = (List<ClothesInfo>) serverInfo.getData();
                        if (list.size() > 0) {
                            ClothesInfo info = list.get(0);
                            colors = StringUtils.getListByStr(info.getColors(), ",");
                            colorAdapter.setList(colors);
                            sizes = StringUtils.getListByStr(info.getSize(), ",");
                            sizeAdapter.setList(sizes);
                            colorNums = StringUtils.getListByStr(info.getColorNumber(), ",");
                            mTvColorNum.setText(colors.size()==0?"":colors.size()+"个");
                            mTvSizeNum.setText(sizes.size()==0?"":sizes.size()+"个");
                        }else {
                            setError();
                        }
                    }

                    @Override
                    public void onError(Response<ServerInfo<List<ClothesInfo>>> response) {
                        showToast("登记信息查询失败");
                        setError();
                    }
                });
    }

    //设置款号不对或者请求错误
    private void setError(){
        colorAdapter.setList(new ArrayList<String>());
        sizeAdapter.setList(new ArrayList<String>());
        mTvColorNum.setText("");
        mTvSizeNum.setText("");
    }

    //根据工号请求姓名
    private void getNameByNum(String wokerNum){
        OkGo.<String>get(BaseUrl.GetName)
                .params("emplno",wokerNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String res = response.body().toString();
                        try {
                            JSONObject object = new JSONObject(res);
                            if(object.has("data")){
                                JSONArray array = object.getJSONArray("data");
                                if(array.length()>0){
                                    JSONObject obj = array.getJSONObject(0);
                                    String name = obj.getString("realName");
                                    mTvName.setText(name);
                                }
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

}
